/*************************************************************************
 * File Name:    Convert_Sorted_List_to_Binary_Search_Tree.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/4 14:41:01
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Convert Sorted List to Binary Search Tree
 | Given a singly linked list where elements are sorted in ascending order,
 | convert it to a height balanced BST.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head)
    {
        vector<TreeNode *> tree;
        
        for (ListNode *p = head; p != NULL; p = p->next) {
            tree.push_back(new TreeNode(p->val));
        }
        int N = tree.size();
        
        int tree_id = dfs(tree, 0, N - 1);
        if (tree_id == -1) return NULL;
        return tree[tree_id];
    }
    
    int dfs(vector<TreeNode*> &tree, int left, int right)
    {
        if (left > right) return -1;
        int mid = left + (right - left) / 2;
        
        int left_id = dfs(tree, left, mid - 1);
        if (left_id != -1) tree[mid]->left = tree[left_id];
        
        int right_id = dfs(tree, mid + 1, right);
        if (right_id != -1) tree[mid]->right = tree[right_id];
        return mid;
    }
};

